package com.jlastu.znb.buy;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.jlastu.znb.R;
import com.jlastu.znb.adapter.buyAdapter;
import com.jlastu.znb.utils.SpUtils;
import com.jlastu.znb.view.GoodsDetailActivity;
import com.jlastu.znb.view.fkActivity;

public class buyActivity extends AppCompatActivity {
    private buyAdapter buyAdapter;
    private ListView buyListView;
    private buyManager buyManager;
    private SpUtils mSpUtils;
    private int goodsId;
    private BroadcastReceiver refreshCartReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.jlastu.znb.REFRESH_CART".equals(intent.getAction())) {
                // 刷新购物车数据
                buyAdapter.notifyDataSetChanged();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buy);
        goodsId = getIntent().getIntExtra("GOODS_ID", -1);
        buyManager = new buyManager(this);
        buyListView = findViewById(R.id.buy_list_view);
        buyAdapter = new buyAdapter(this, buyManager.getbuyItems());
        buyListView.setAdapter(buyAdapter);
        refreshCartReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("com.jlastu.znb.REFRESH_CART".equals(intent.getAction())) {
                    // 刷新 Adapter 数据
                    buyAdapter.clear();
                    buyAdapter.addAll(buyManager.getbuyItems());
                    buyAdapter.notifyDataSetChanged();
                }
            }
        };
        registerReceiver(refreshCartReceiver, new IntentFilter("com.jlastu.znb.REFRESH_CART"));

        buyListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                buyItem itemToRemove = buyAdapter.getItem(position);
                buyManager.removeFromBuyByGoodsId(itemToRemove.getId());
                buyAdapter.remove(itemToRemove);
                buyAdapter.notifyDataSetChanged();
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(refreshCartReceiver);
    }
    @Override
    protected void onResume() {
        super.onResume();
        buyAdapter.notifyDataSetChanged();
    }
}